package com.codeoss.framework.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.codeoss.framework.context.YunContext;

public class MiYunYunFilter implements Filter {
	private static final Logger logger = LoggerFactory.getLogger(MiYunYunFilter.class);
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterchain)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
		httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
		// httpServletResponse.setHeader("Access-Control-Allow-Headers",
		// "x-requested-with,content-type,token,authorization");
		httpServletResponse.setHeader("Access-Control-Allow-Headers", "X-Token,Content-Type");
		httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
		if(httpServletRequest.getMethod().toUpperCase().equals("OPTIONS")) {
			return;
		}
		try {
			filterchain.doFilter(request, response);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("",e);
			throw e;
			
		} finally {
			YunContext.dispose();
		}
	}

}
